package cn.wolfcode.web.modules.customer.controller;

import cn.wolfcode.web.commons.entity.LayuiPage;
import cn.wolfcode.web.commons.utils.CityUtils;
import cn.wolfcode.web.commons.utils.LayuiTools;
import cn.wolfcode.web.commons.utils.SystemCheckUtils;
import cn.wolfcode.web.modules.BaseController;
import cn.wolfcode.web.modules.linkman.entity.TbCustLinkman;
import cn.wolfcode.web.modules.linkman.service.ITbCustLinkmanService;
import cn.wolfcode.web.modules.log.LogModules;
import cn.wolfcode.web.modules.sys.entity.SysUser;
import cn.wolfcode.web.modules.sys.form.LoginForm;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.conditions.query.LambdaQueryChainWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;


import cn.wolfcode.web.modules.customer.entity.TbCustomer;
import cn.wolfcode.web.modules.customer.service.ITbCustomerService;


import link.ahsj.core.annotations.AddGroup;
import link.ahsj.core.annotations.SameUrlData;
import link.ahsj.core.annotations.SysLog;
import link.ahsj.core.annotations.UpdateGroup;
import link.ahsj.core.entitys.ApiModel;
import link.ahsj.core.exception.AppServerException;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.List;

/**
 * @author sjh
 * @since 2024-04-15
 */
@Controller
@RequestMapping("customer")
public class TbCustomerController extends BaseController {

    @Autowired
    private ITbCustomerService entityService;

    @Autowired
    private ITbCustLinkmanService custLinkmanService;


    private static final String LogModule = "TbCustomer";

    @GetMapping("/list.html")
    public ModelAndView list(ModelAndView mv) {



        mv.addObject("citys", CityUtils.citys);

        mv.setViewName("cust/customer/list");
        return mv;
    }

    @RequestMapping("/add.html")
    @PreAuthorize("hasAuthority('cust:customer:add')")
    public ModelAndView toAdd(ModelAndView mv) {
        mv.addObject("citys", CityUtils.citys);
        mv.setViewName("cust/customer/add");
        return mv;
    }

    @GetMapping("/{id}.html")
    @PreAuthorize("hasAuthority('cust:customer:update')")
    public ModelAndView toUpdate(@PathVariable("id") String id, ModelAndView mv) {
        mv.setViewName("cust/customer/update");
        mv.addObject("obj", entityService.getById(id));
        mv.addObject("id", id);
        mv.addObject("citys", CityUtils.citys);
        return mv;
    }

    @RequestMapping("list")
    @PreAuthorize("hasAuthority('cust:customer:list')")
    public ResponseEntity page(LayuiPage layuiPage,String parameterName,String cityId,String openStatus) {


        SystemCheckUtils.getInstance().checkMaxPage(layuiPage);

        IPage page = new Page<>(layuiPage.getPage(), layuiPage.getLimit());

        //分页查询
       // LambdaQueryChainWrapper<TbCustomer> queryWrapper = entityService.lambdaQuery();

//        queryWrapper.
//                like(!StringUtils.isEmpty(parameterName),TbCustomer::getCustomerName,parameterName).or().
//                like(!StringUtils.isEmpty(parameterName),TbCustomer::getLegalLeader,parameterName);

        LambdaQueryChainWrapper<TbCustomer> tbCustomerLambdaQueryChainWrapper = entityService.lambdaQuery();
        tbCustomerLambdaQueryChainWrapper.eq(!StringUtils.isEmpty(cityId), TbCustomer::getProvince,cityId)
                .eq(!StringUtils.isEmpty(openStatus), TbCustomer::getOpenStatus,openStatus)
                .and(!StringUtils.isEmpty(parameterName), q -> q.like(TbCustomer::getCustomerName, parameterName).or().like(TbCustomer::getLegalLeader, parameterName));


        page = tbCustomerLambdaQueryChainWrapper.page(page);

        //处理省份数据
        List<TbCustomer> lists = page.getRecords();

        for (TbCustomer list : lists) {
            String cityValue = CityUtils.getCityValue(list.getProvince());
            list.setProvinceName(cityValue);
        }

        return ResponseEntity.ok(LayuiTools.toLayuiTableModel(page));

    }

    @SameUrlData
    @PostMapping("save")
    @SysLog(value = LogModules.SAVE, module =LogModule)
    @PreAuthorize("hasAuthority('cust:customer:add')")
    public ResponseEntity<ApiModel> save(@Validated({AddGroup.class}) @RequestBody TbCustomer entity, HttpServletRequest request) {

        entity.setInputTime(LocalDateTime.now());

        SysUser user = (SysUser) request.getSession().getAttribute(LoginForm.LOGIN_USER_KEY);

        entity.setInputUserId(user.getUserId());

        Integer count = entityService.lambdaQuery().eq(TbCustomer::getCustomerName, entity.getCustomerName()).count();
        if (count>0){
            throw new AppServerException("企业名称以及存在");
        }

        entityService.save(entity);

        return ResponseEntity.ok(ApiModel.ok());
    }

    @SameUrlData
    @SysLog(value = LogModules.UPDATE, module = LogModule)
    @PutMapping("update")
    @PreAuthorize("hasAuthority('cust:customer:update')")
    public ResponseEntity<ApiModel> update(@Validated({UpdateGroup.class}) @RequestBody TbCustomer entity) {


        entity.setUpdateTime(LocalDateTime.now());

        Integer count = entityService.lambdaQuery().
                eq(TbCustomer::getCustomerName, entity.getCustomerName()).
                 ne(TbCustomer::getId, entity.getId()).count();
        if (count > 0){
            throw new AppServerException("这个客户已经存在！");
        }
        entityService.updateById(entity);

        return ResponseEntity.ok(ApiModel.ok());

    }

    @SysLog(value = LogModules.DELETE, module = LogModule)
    @DeleteMapping("delete/{id}")
    @PreAuthorize("hasAuthority('cust:customer:delete')")
    public ResponseEntity<ApiModel> delete(@PathVariable("id") String id) {

        entityService.removeById(id);

        custLinkmanService.lambdaUpdate().eq(TbCustLinkman::getCustId,id).remove();

        return ResponseEntity.ok(ApiModel.ok());
    }

}
